# -*- coding: utf-8 -*-
import scrapy
from copy import deepcopy

class MeishichinaSpider(scrapy.Spider):
    name = 'meishichina'
    allowed_domains = ['meishichina.com']
    start_urls = ['https://home.meishichina.com/search/番茄炒蛋','https://home.meishichina.com/search/牛肉面']

    def parse(self, response):
        datalist = response.xpath("//div[@class='ui_list_1']/ul/li/div[@class='detail']/h4/a")
        for data in datalist:
            item = {}
            item["source"] = "美食天下"
            item["href"] = data.xpath("./@href").extract_first()
            item["title"] = data.xpath("./em/text()").extract_first()
            if item["title"] is None:
                continue
            if item["href"] is not None:
                yield scrapy.Request(
                    item["href"],
                    callback=self.parse_food_info,
                    meta={"item": deepcopy(item)}
                )

    def parse_food_info(self, response):
        item = response.meta["item"]
        datalist = response.xpath("//fieldset[@class='particulars']")
        for data in datalist:
            name = data.xpath("./legend/text()").extract_first()
            if name is None:
                continue
            # if name not in item.keys():
            #     item[name] = []
            item[name] = data.xpath(".//b/text()").extract()
            # if material is None:
            #     continue
            # item[name].append(material)
        print(item)
